import "./AddBackgrounParagraphModal.scss";
import React, {
  forwardRef,
  useState,
  useImperativeHandle,
  useContext,
  ChangeEvent,
} from "react";
import { Modal, Input } from "antd";
import { TopicNodeActionType, TopicType } from "../../../../utils/types";
import comDocContext from "./../../../../context/DocContext";
import {
  getChangeEventValue,
  getTopicMaxBackgroundIndex,
  isEmpty,
  toastShort,
} from "../../../../utils";

interface Props {
  onFinish?: (pagraphText: string) => void;
}

const AddTopicMoal = (props: Props, ref: any) => {
  useImperativeHandle(ref, () => ({
    openModal: openModal,
  }));

  const [submitLoading, setSubmitLoading] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);

  const { comDocInstance, _setComDocInstance } = useContext(comDocContext);
  const [currentTopicNode, setCurrentTopicNode] = useState<TopicType>(null);

  const [pagraphText, setPagraphText] = useState<string>("");

  const { onFinish } = props;

  const openModal = (textTopic: TopicType) => {
    setIsModalOpen(true);
    setCurrentTopicNode(textTopic);
  };

  const handleConfirm = () => {
    if (isEmpty(pagraphText)) {
      return toastShort("error", "请先输入大纲段落文本");
    }
    setIsModalOpen(false);
    onFinish && onFinish(pagraphText);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const onParagraphTextChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
    setPagraphText(getChangeEventValue(e));
  };

  return (
    <Modal
      title={"添加大纲背景文本"}
      open={isModalOpen}
      onOk={handleConfirm}
      onCancel={handleCancel}
      okText={"确 认"}
      cancelText={"取 消"}
      width={672}
      maskClosable={false}
      confirmLoading={submitLoading}
      centered
    >
      <div className="custom-modal-container">
        <div className="add-paragraph-block">
          <Input.TextArea
            placeholder={"粘贴背景文本到此处"}
            rows={21}
            value={pagraphText}
            onChange={onParagraphTextChange}
            allowClear
            maxLength={8000}
            showCount
          />
        </div>
      </div>
    </Modal>
  );
};

export default forwardRef(AddTopicMoal);
